package com.sz.controller.frame;

import com.hankcs.hanlp.HanLP;
import com.sz.bean.Page;
import com.sz.lucene.TikuIndex;
import com.sz.pojo.frame.Tiku;
import com.sz.pojo.frame.ZiDian;
import com.sz.service.frame.TikuService;
import com.sz.service.frame.ZiDianService;
import com.sz.util.HanyuPinyinHelper;
import com.sz.util.ToolStr;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apdplat.word.WordSegmenter;
import org.apdplat.word.segmentation.Word;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * 用户管理
 *
 * @author 哈尼玛
 */
@Controller
public class TikuController extends BaseController<Tiku> {
    /**
     * 对应pojo的名字
     */
    public static final String POJO_NAME = "tiku";
    /**
     * 权限url前缀
     */
    public static final String PERMISSION_URL_PREFIX = PERMISSION_PREFIX + POJO_NAME;
    /**
     * 列表
     */
    public static final String LIST_URL = PERMISSION_URL_PREFIX + "/list";
    public static final String WEB_LIST_URL = WEB_PERMISSION_PREFIX + POJO_NAME + "/weblist";
    public static final String MODIFY_URL = PERMISSION_URL_PREFIX + "/modify";
    public static final String SAVE_URL = PERMISSION_URL_PREFIX + "/save";
    public static final String SAVE_ALL_URL = PERMISSION_URL_PREFIX + "/saveall";
    public static final String REMOVE_URL = PERMISSION_URL_PREFIX + "/remove";

    @Autowired
    private TikuService tikuService;
    @Autowired
    private TikuIndex tikuIndex;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private ZiDianService ziDianService;


    public TikuController() {
        super(POJO_NAME);
    }

    @RequestMapping(LIST_URL)
    public String list(Model m, String key, String q, Page page) {
        //根据关键词搜索 词库
        HashMap<String, Object> parm = new HashMap<String, Object>();
        if (!ToolStr.isEmpty(key)) {
            parm.put(" keysWords = ", key);
        }
        List<Tiku> list = tikuService.find4Page(page, parm);
        m.addAttribute("tikulist", list);
        m.addAttribute("key", key);
        m.addAttribute("q", q);
        return url("list");
    }

    /**
     * 前端访问
     *
     * @param m
     * @return
     */
    @RequestMapping(WEB_LIST_URL)
    public String weblist(Model m, String question) {
        final List<Tiku> list = new ArrayList<>();

        if (!ToolStr.isEmpty(question)) {
            question = question.trim();
        }

        if (list == null || list.size() == 0) {
            Document doc = null;
            try {
                doc = Jsoup.connect("http://www.baidu.com/s?wd=" + question).get();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Integer id = 1;
            do {
                Elements div = doc.body().select("#" + id);
                String a = div.select("a").first().attr("href");
                Document doc2;
                try {
                    doc2 = Jsoup.connect(a).get();
                    Tiku tiku = new Tiku();
                    if (!ToolStr.isEmpty(doc2.title()) && !ToolStr.isEmpty(doc2.body().text())) {
                        List<String> sentenceList = HanLP.extractSummary(doc2.body().text(), 1);
                        tiku.setQuesetion("");
                        tiku.setAnswer(sentenceList.get(0));
                        list.add(tiku);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                id++;
            } while (list.size() < 5);
            StringBuffer text = new StringBuffer();
            list.forEach(tiku -> {
                text.append(tiku.getAnswer());
            });

            // List<String> list = HanLP.extractSummary( text.toString() , 1);

            m.addAttribute("question", question);
            m.addAttribute("tikulist", list);

            return "../../web/index2";
        } else {
            return "../../web/index";
        }
    }

    public String weblist(Model m, String question, Integer type, Page page) {
        final List<Tiku> list = new ArrayList<>();
        //根据关键词搜索 词库
        if (!ToolStr.isEmpty(question)) {
            question = question.trim();

            String cuoci = null;
            String jiucuo = null;
            //判断是为查差错词不必判断是否为错词
            if (type != null && 2 == type) {
                //根据错词查询数据库
                cuoci = question;
                //直接like question
                Map<String, Object> map = new HashMap<>();
                map.put(" quesetion like ", cuoci);
                list.addAll(tikuService.find4Params(map));
            } else {
                //判断是否为字典错词，如果是字典措辞添加错词查纠错词；
                Map<String, Object> params = new HashMap<>();
                params.put("name like", ToolStr.fuzzy(question));
                List<ZiDian> ziDianList = ziDianService.find4Params(params);
                if (ToolStr.isEmpty(ziDianList)) {
                    Map<String, Object> pinyinParams = new HashMap<>();
                    pinyinParams.put("pinyin like", ToolStr.fuzzy(HanyuPinyinHelper.toHanyuPinyin(question)));
                    List<ZiDian> pinyinList = ziDianService.find4Params(pinyinParams);
                    if (!ToolStr.isEmpty(pinyinList)) {
                        jiucuo = pinyinList.get(0).getName();
                        cuoci = question;
                    }
                }

                list.clear();
                addResultNoDuplicate(list, buildTiKuSet(question, 1));
                addResultNoDuplicate(list, buildTiKuSet(question, 2));
                List<Word> words = WordSegmenter.seg(question);
                words.forEach(word -> {
                    try {
                        String wordText = word.getText();
                        addResultNoDuplicate(list, buildTiKuSet(wordText, 1));
                        addResultNoDuplicate(list, buildTiKuSet(wordText, 2));
                        addResultNoDuplicate(list, tikuIndex.searchArticle(httpServletRequest, wordText));
                    } catch (Exception e) {
                    }
                });
            }
            //什么都没有查出来的情况
            if (list == null || list.size() == 0) {
                Document doc = null;
                try {
                    if (jiucuo != null) {
                        doc = Jsoup.connect("http://www.baidu.com/s?wd=" + jiucuo).get();
                    } else {
                        doc = Jsoup.connect("http://www.baidu.com/s?wd=" + question).get();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Integer id = 1;
                do {
                    Elements div = doc.body().select("#" + id);
                    String a = div.select("a").first().attr("href");
                    Document doc2;
                    try {
                        doc2 = Jsoup.connect(a).get();
                        Tiku tiku = new Tiku();
                        if (!ToolStr.isEmpty(doc2.title()) && !ToolStr.isEmpty(doc2.body().text())) {
                            tiku.setQuesetion(doc2.title());
                            tiku.setAnswer(doc2.body().text());
                            list.add(tiku);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    id++;
                } while (list.size() < 5);
            }
            if (cuoci != null && jiucuo != null) {
                m.addAttribute("jiucuo", jiucuo);
                m.addAttribute("cuoci", cuoci);
            }
            m.addAttribute("question", question);
            m.addAttribute("tikulist", list);
            return "../../web/index2";
        } else {
            return "../../web/index";
        }
    }

    // List<Word> words = WordSegmenter.seg(question, SegmentationAlgorithm.FullSegmentation);
    // SegmentationAlgorithm的可选类型为：
    // 正向最大匹配算法：MaximumMatching
    // 逆向最大匹配算法：ReverseMaximumMatching
    // 正向最小匹配算法：MinimumMatching
    // 逆向最小匹配算法：ReverseMinimumMatching
    // 双向最大匹配算法：BidirectionalMaximumMatching
    // 双向最小匹配算法：BidirectionalMinimumMatching
    // 双向最大最小匹配算法：BidirectionalMaximumMinimumMatching
    // 全切分算法：FullSegmentation
    // 最少分词算法：MinimalWordCount
    // 最大Ngram分值算法：MaxNgramScore

    @RequestMapping(MODIFY_URL)
    public String modify(Model m, Long id) {
        if (id != null) {
            m.addAttribute("tiku", tikuService.get(id));
        }
        return url("tiku");
    }

    @RequestMapping(REMOVE_URL)
    public String remove(Model m, String ids) {
        tikuService.remove(ids);
        return redirectUrl(LIST_URL);
    }

    @RequestMapping(SAVE_URL)
    public String save(Model m, Tiku tiku) {
        tiku.setTime(getNowDate());
        tikuService.save(tiku);
        return redirectUrl(LIST_URL);
    }


    @RequestMapping(SAVE_ALL_URL)
    @ResponseBody
    public String saveall(Model m) {
        //获取根目录
        // E:\项目练习\题库\题库\问答对.xlsx
        ArrayList<Integer> tihaolist = new ArrayList<>();
        ArrayList<Tiku> tikulist = new ArrayList<>();

        XSSFWorkbook excel;
        try {
            excel = new XSSFWorkbook("E:\\项目练习\\题库\\题库\\问答对.xlsx");
            XSSFSheet sheet1 = excel.getSheetAt(0);
            int rowNum = sheet1.getLastRowNum();
            for (int i = 1; i <= rowNum; i++) {
                Tiku t = new Tiku();
                XSSFRow row = sheet1.getRow(i);
                if (row != null) {
                    // 获取到Excel文件中的所有的列
                    int cells = row.getPhysicalNumberOfCells();
                    for (int j = 1; j < cells; j++) {
                        // 获取到列的值
                        Cell cell = row.getCell(j);
                        if (cell != null) {
                            switch (cell.getCellTypeEnum()) {
                                case STRING:
                                    if (j == 1) {
                                        t.setQuesetion(cell.getStringCellValue());
                                    }
                                    if (j == 2) {
                                        t.setAnswer(cell.getStringCellValue());
                                    }
                                    if (j > 2) {
                                        System.out.println("j大于2");
                                    }
                                    break;
                                default:
                                    if (j == 0) {
                                        tihaolist.add(Double.valueOf(cell.getNumericCellValue()).intValue());
                                    } else {
                                        System.out.println("值为：" + cell.toString());
                                    }
                                    break;
                            }
                        }

                    }
                }
                tikulist.add(t);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        tikulist.forEach((tiku) -> {
            if (!ToolStr.isEmpty(tiku.getQuesetion()) && !ToolStr.isEmpty(tiku.getAnswer())) {
                tiku.setTime(new Date());
                tikuService.save(tiku);
            }
        });
        return redirectUrl(LIST_URL);
    }


    /**
     * 构建TikuSet，根据要搜索的词：text
     *
     * @param text
     * @param type--1：汉字；2：拼音；
     * @return
     */
    private Set<Tiku> buildTiKuSet(String text, int type) {
        Set<Tiku> tiKuSet = new HashSet<>();
        Map<String, Object> params = new HashMap<>();
        if (type == 2) {
            params.put("pinyin like", ToolStr.fuzzy(HanyuPinyinHelper.toHanyuPinyin(text)));
        } else {
            params.put("name like", ToolStr.fuzzy(text));
        }
        List<ZiDian> ziDianList = ziDianService.find4Params(params);
        if (!ToolStr.isEmpty(ziDianList)) {
            for (ZiDian ziDian : ziDianList) {
                String content = ziDian.getName();
                try {
                    tiKuSet.addAll(tikuIndex.searchArticle(httpServletRequest, content));
                } catch (Exception e) {
                }
            }
        }
        return tiKuSet;
    }

    /**
     * 对list添加新的list，不添加重复元素
     *
     * @param list
     * @param newList
     */
    private void addResultNoDuplicate(List<Tiku> list, Collection<Tiku> newList) {
        for (Tiku tiku : newList) {
            if (!list.contains(tiku)) {
                list.add(tiku);
            }
        }
    }


}